package com.mycompany.app.service;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.mycompany.app.model.User;
import com.mycompany.app.user.dao.IPerfilDAO;
import com.mycompany.app.user.dao.IUserDAO;

/*
 * Spring-security requires an implementation of UserDetailService. 
 */
@Service("userDetailsService")
public class UserLoginService implements UserDetailsService {
	
	protected final Log logger = LogFactory.getLog(getClass());
	  
	@Resource
	private IUserDAO userDAO;
	
	@Resource
	private IPerfilDAO perfilDAO;
	

	public UserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException{
		logger.info(userDAO+"Login username :"+username);
		User user =userDAO.getUserByUserName(username);
		logger.info("user load :"+user);
		if (user == null) {
			throw new UsernameNotFoundException("UserAccount for name \""
					+ username + "\" not found.");
		}
		
		return user;
	}
	

	@PostConstruct
	public void init() {
		
		// sample roles		
	/*	Collection<GrantedAuthority> adminAuthorities = new ArrayList<GrantedAuthority>();
		adminAuthorities.add(new GrantedAuthorityImpl("ROLE_ADMIN"));
		
		Collection<GrantedAuthority> userAuthorities = new ArrayList<GrantedAuthority>();
		userAuthorities.add(new GrantedAuthorityImpl("ROLE_REGISTERED"));
		
		boolean enabled = true;
		boolean accountNonExpired = true;
		boolean credentialsNonExpired = true;
		boolean accountNonLocked = true;
		
		// sample users with roles set
		users.put("admin", new org.springframework.security.core.userdetails.User("admin", "admin", enabled, accountNonExpired,
				credentialsNonExpired, accountNonLocked, adminAuthorities));
		
		users.put("user", new org.springframework.security.core.userdetails.User("user", "user", enabled, accountNonExpired,
				credentialsNonExpired, accountNonLocked, userAuthorities));*/
	}


	public IUserDAO getUserDAO() {
		return userDAO;
	}


	public void setUserDAO(IUserDAO userDAO) {
		this.userDAO = userDAO;
	}


	public IPerfilDAO getPerfilDAO() {
		return perfilDAO;
	}


	public void setPerfilDAO(IPerfilDAO perfilDAO) {
		this.perfilDAO = perfilDAO;
	}

}
